package com.wc;

import com.Parser.MetricbeatJSONKeyValueServerDeserializationSchema;
import com.Pojo.ServerLog;
import com.alibaba.fastjson.JSONObject;
import com.sink.MetricBeatSink;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.connector.kafka.source.reader.deserializer.KafkaRecordDeserializationSchema;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 谢秉均
 * @description  处理metricbeat的system.yml模块的数据采集
 * @date 2025/3/7--9:47
 */
public class MetricMain {

    private static final Logger logger = LoggerFactory.getLogger(MetricMain.class);


    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //nginx主题
        String topic="ServerResources";

        // 1.初始化 KafkaSource 实例
        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("10.52.3.34:9092,10.52.3.36:9092")   // 必填：指定broker连接信息 (为保证高可用,建议多指定几个节点)
                .setTopics(topic)                               // 必填：指定要消费的topic
                .setGroupId("test-group")                                 // 必填：指定消费者的groupid(不存在时会自动创建)
                .setDeserializer(KafkaRecordDeserializationSchema.of(
                        new MetricbeatJSONKeyValueServerDeserializationSchema()  //IIS解析器
                ))
//                .setValueOnlyDeserializer(new SimpleStringSchema())     // 必填：指定反序列化器(用来解析kafka消息数据，转换为flink数据类型)
                .setStartingOffsets(OffsetsInitializer.latest())      // 可选：指定启动任务时的消费位点（不指定时，将默认使用 OffsetsInitializer.earliest()）
                .build();



        // 2.通过 fromSource + KafkaSource 获取 DataStreamSink
        DataStreamSource<String> streamSource = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");



        SinkFunction<String> sink = new MetricBeatSink("mssql").GetMetricSinkString("dbatest","1234.com","10.52.4.9", "dbtest");


        //过滤掉异常数据流
        DataStream<String> streamSource2 =  streamSource.filter(new FilterFunction<String>() {
                        @Override
                        public boolean filter(String s) throws Exception {
                        ServerLog log = JSONObject.parseObject(s,ServerLog.class);
                        boolean result = true;
                        if(log.getMetric() == null || log.getResult() == null){
                            //logger.info("filter："+log.getContext()); //调试查看被过滤的信息
                            result = false;
                        }

                        return result;
                     }
              }

        );

//        streamSource2.print();  //调试
        streamSource2.addSink(sink);
        //启动程序并设置JOB名称
        env.execute("SH-TEST-Linux-MSSQL-10.52.4.9-Metric");
    }
}
